package com.ebt.m.customer.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.listview.pulltorefresh.PullToRefreshView;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.adapter.AdapterCustomerAttachment;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerAtta;
import com.ebt.m.customer.event.EventCustomerFloatingButtonAction;
import com.ebt.m.customer.event.EventRefreshAttachment;
import com.ebt.m.customer.fragment.BaseLazySwipeRefreshFragment;
import com.ebt.m.customer.net.json.CustomerAttaListJson;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.DisplayUtil;
import com.ebt.m.data.entity.EntityCustomerAttachment;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.EBTProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 客户详情-附件
 */
public class FragmentCustomerAttachment extends BaseLazySwipeRefreshFragment {

    @BindView(R.id.lv_content)
    ListView mListView;
    @BindView(R.id.iv_empty)
    ImageView mEmptyImageView;
    @BindView(R.id.tv_empty)
    TextView mEmptyTextView;
    @BindView(R.id.btn_empty)
    Button mEmptyButton;
    @BindView(R.id.empty_container)
    LinearLayout mEmptyView;
    @BindView(R.id.load_refresh_net)
    TextView loadRefreshNet;
    @BindView(R.id.load_refresh)
    TextView loadRefresh;
    @BindView(R.id.progress)
    EBTProgress progress;
    Unbinder unbinder;
    private View noNetContainer;
    private View netSlowContainer;

    private Bundle mGetBundle;
    private String mCustomerUUID;
    private List<CustomerAtta> mAttas = new ArrayList<>();
    private List<EntityCustomerAttachment> mAttaEntities = new ArrayList<>();
    private AdapterCustomerAttachment mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initArgs();
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_customer_attachment2;
    }

    @Override
    protected void onSwipeRefresh(PullToRefreshView swipeRefreshLayout) {
        initValues(false);
    }

    @Override
    protected void onCreateContentView(View contentView, Bundle savedInstanceState) {
        unbinder = ButterKnife.bind(this, contentView);
        noNetContainer = contentView.findViewById(R.id.no_net_container);
        netSlowContainer = contentView.findViewById(R.id.net_slow_container);
        mEmptyButton.setVisibility(View.VISIBLE);
        mEmptyButton.setText("新建附件");
        mEmptyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new EventCustomerFloatingButtonAction(EventCustomerFloatingButtonAction.Attachment));
            }
        });

        View v = new View(getContext());
        v.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                DisplayUtil.sp2px(getContext().getApplicationContext(), 120)));
        mListView.addFooterView(v, null, false);

        mAttas.clear();
        if (mAdapter == null) {
            mAdapter = new AdapterCustomerAttachment(getContext(), mAttaEntities);
            mListView.setAdapter(mAdapter);
        }
        setAbsListViewTarget(mListView);
    }

    /**
     * 空图和错误图片显示逻辑
     *
     * @param empty
     * @param no_net
     * @param net_slow
     */
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
        if (empty) {
            mEmptyView.setVisibility(View.VISIBLE);
            mEmptyTextView.setText("暂无附件哦");
            mEmptyImageView.setImageResource(R.drawable.ic_empty_attachment);
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
        noNetContainer.setVisibility(no_net ? View.VISIBLE : View.GONE);
        netSlowContainer.setVisibility(net_slow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onFirstUserVisible() {
        super.onFirstUserVisible();
        getView().postDelayed(new Runnable() {
            @Override
            public void run() {
                showProgress();
                initValues(true);
            }
        }, CustomerConstant.Delay.FRAGMENT_UPDATE_DELAY);
    }

    private void showProgress() {
        if (progress != null) {
            progress.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgress() {
        if (progress != null) {
            progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventRefreshAttachment event) {
        if (event != null) {
            if (event.showRefresh) {
                showRefresh();
            }
            initValues(false);
        }
    }


    private void initArgs() {
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            mCustomerUUID = mGetBundle.getString(CustomerConstant.CUSTOMER_UUID);
        }
    }

    private void initValues(boolean fromInit) {
        if (!TextUtils.isEmpty(mCustomerUUID)) {
            getCustomerAttaList(mCustomerUUID);
        }
    }

    private void getCustomerAttaList(String customerId) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getCustomerAllAttachment(customerId).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerAttaListSubscriber());
    }

    private Observer<CustomerAttaListJson> getCustomerAttaListSubscriber() {
        return new Observer<CustomerAttaListJson>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
                hideRefresh();
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                UIHelper.makeToast(getContext(), getString(R.string.network_fail));
                if (NetUtils.isNetworkAvailable(getContext())) {
                    showEmpty(false, false, true);
                } else {
                    showEmpty(false, true, false);
                }
                hideRefresh();
                hideProgress();
            }

            @Override
            public void onNext(CustomerAttaListJson customerAttaListJson) {
                if (customerAttaListJson == null || customerAttaListJson.error != null) {
                    showEmpty(false, false, true);
                } else if (customerAttaListJson.data == null) {
                    showEmpty(true, false, false);
                } else {
                    showAttaList(customerAttaListJson);
                }
                hideRefresh();
                hideProgress();
            }
        };
    }

    private void showAttaList(CustomerAttaListJson customerAttaListJson) {
        List<CustomerAtta> list = customerAttaListJson.data.listCustomerAttachment;
        List<EntityCustomerAttachment> listEntities = CustomerConvertUtil.convertListAttaJsonToEntity(list);

        mAttaEntities.clear();
        if (listEntities != null) {
            mAttaEntities.addAll(listEntities);
        }

        if (mAdapter == null) {
            mAdapter = new AdapterCustomerAttachment(getContext(), mAttaEntities);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mListView.setAdapter(mAdapter);
        showEmpty(mAttaEntities.size() <= 0, false, false);
    }

    public static FragmentCustomerAttachment newInstance(String customerUuid) {
        Bundle bundle = new Bundle();
        bundle.putString(CustomerConstant.CUSTOMER_UUID, customerUuid);

        FragmentCustomerAttachment fragmentCustomerAttachment2 = new FragmentCustomerAttachment();
        fragmentCustomerAttachment2.setArguments(bundle);
        return fragmentCustomerAttachment2;
    }

    @OnClick({R.id.btn_empty, R.id.load_refresh_net, R.id.load_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_empty:
                EventBus.getDefault().post(new EventCustomerFloatingButtonAction(EventCustomerFloatingButtonAction.Note));
                break;
            case R.id.load_refresh_net:
                initValues(false);
            case R.id.load_refresh:
                initValues(false);
                break;
        }
    }
}